package com.xiaoshou.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.xiaoshou.pojo.Files;
import com.xiaoshou.pojo.Question;

@Repository
public class FilesDao extends BaseDao<Files, String> {

	public void saveFileOfQuestion(Files f, Question q) {
		String sql = "insert into files values(:id,:filename,:filesize,:md5,:fileurl,:uploadtime,:lastupdatetime,:userid)";
		String sql2 = "insert into question_files_rel values(:questionid,:filesid)";
		Query query = getSession().createSQLQuery(sql);
		Query query2 = getSession().createSQLQuery(sql2);

		String fileURI = f.getFileurl();
		fileURI = fileURI.replaceAll("\\\\", "\\\\\\\\");
		query.setParameter("id", f.getId());
		query.setParameter("filename", f.getFilename());
		query.setParameter("filesize", f.getFilesize());
		query.setParameter("md5", f.getMd5());
		query.setParameter("userid", f.getUser().getId());
		query.setParameter("fileurl", fileURI.toString());
		query.setParameter("uploadtime", f.getUploadtime());
		query.setParameter("lastupdatetime", f.getLastupdatetime());

		query2.setParameter("filesid", f.getId());
		query2.setParameter("questionid", q.getId());

		query.executeUpdate();

		query2.executeUpdate();

	}

	public List<String> getFileMd5List() {
		String hql = "select md5 from Files ";
		Query query = getSession().createQuery(hql);
		@SuppressWarnings("unchecked")
		List<String> list = query.list();
		return list;
	}

	public void updateFiles(Files f) {
		String sql = "UPDATE files SET "
				+ "filename=:filename,filesize=:filesize,md5=:md5,"
				+ "filetypeid=:filetypeid,userid=:userid,fileurl=:fileurl,"
				+ "uploadtime=:uploadtime,lastupdatetime=:lastupdatetime WHERE id=:id";
		Query query = getSession().createSQLQuery(sql);
		query.setParameter("id", f.getId());
		query.setParameter("filename", f.getFilename());
		query.setParameter("filesize", f.getFilesize());
		query.setParameter("md5", f.getMd5());
		query.setParameter("userid", f.getUser().getId());
		query.setParameter("fileurl", f.getFileurl());
		query.setParameter("uploadtime", f.getUploadtime());
		query.setParameter("lastupdatetime", f.getLastupdatetime());
		query.executeUpdate();
	}

	public void delFileInRel(Files files) {
		String sql = "DELETE FROM question_files_rel WHERE filesid = :filesid";
		Query query = getSession().createSQLQuery(sql);
		query.setParameter("filesid", files.getId());
		query.executeUpdate();

	}

	public void deleteFileInPage(Files files) {
		String sql = "DELETE FROM question_files_rel WHERE filesid=:filesid";
		String sql1 = "DELETE FROM files WHERE id=:id";
		Query query = getSession().createSQLQuery(sql);
		query.setParameter("filesid", files.getId());
		query.executeUpdate();
		
		Query query1 = getSession().createSQLQuery(sql1);
		query1.setParameter("id", files.getId());
		query1.executeUpdate();
	}

}
